package com.jielihaofeng.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @author Johnnie Wind
 * @description ByteBuf 测试
 * @date 2021/11/10 11:40
 */
public class TestByteBuf {
    public static void main(String[] args) {
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        // ByteBuf实例是哪个类
        System.out.println(buf.getClass());
        // ByteBuf的最大容量
        System.out.println(buf.maxCapacity());

        // 输出当前容量：256
        System.out.println(buf.capacity());
        // 详细输出
        // 256
        // read index:0 write index:0 capacity:256
        log(buf);

        // buf写入300个字节
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 300; i++) {
            sb.append("a");
        }
        buf.writeBytes(sb.toString().getBytes());
        // 输出当前容量：512，自动扩容了一倍
        System.out.println(buf.capacity());
        // 详细输出
        // 512
        // read index:0 write index:300 capacity:512
        log(buf);

    }

    /**
     * @description ByteBuf 详细信息输出
     * @author Johnnie Wind
     * @date 2021/11/10 14:09
     * @Param [buffer]
     * @return void
     */
    public static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(" maxCapacity:").append(buffer.maxCapacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
